package com.chenss.dragonser.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.chenss.dragonser.R;
import com.chenss.dragonser.activity.OrderDetailActivity;
import com.chenss.dragonser.activity.OrderDetailInfoActivity;
import com.chenss.dragonser.activity.OrderReturnDetailActivity;
import com.chenss.dragonser.activity.QrPicActivity;
import com.chenss.dragonser.adapter.OrderListAdapter;
import com.chenss.dragonser.adapter.OrderReturnListAdapter;
import com.chenss.dragonser.app.AppInfo;
import com.chenss.dragonser.app.Constant;
import com.chenss.dragonser.base.BaseAdp;
import com.chenss.dragonser.base.BaseFragment;
import com.chenss.dragonser.listener.OnMyDialogTwoListener;
import com.chenss.dragonser.model.OrderListModel;
import com.chenss.dragonser.model.OrderRetrunListModel;
import com.chenss.dragonser.network.NetworkRequest;
import com.chenss.dragonser.network.RequestCallbcak;
import com.chenss.dragonser.response.OrderListResponse;
import com.chenss.dragonser.response.OrderReturnListResponse;
import com.chenss.dragonser.utils.GsonUtil;
import com.chenss.dragonser.utils.ToastUtil;
import com.chenss.dragonser.view.XDialogTwo;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;

import org.json.JSONException;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class OrderFragment extends BaseFragment implements OnMyDialogTwoListener, RequestCallbcak, BaseRefreshListener {
    TextView tv_page_title;
    TextView tv_right;
    private TextView tv_tab_left;
    private TextView tv_tab_right;
    private TextView tv_tab_center;
    XDialogTwo dialogTwo;
    ListView mListView;
    List<OrderListModel> list = new ArrayList<>();
    List<OrderRetrunListModel> returnList = new ArrayList<>();
    OrderListAdapter listAdapter;
    OrderReturnListAdapter returnListAdapter;
    public NetworkRequest networkRequest;//网络请求
    public ArrayMap<String, String> parmMap;//请求参数封装
    int type = 1;//获取订单数据类型 1 untreated：未处理，2 treated：已处理 3.退单

    PullToRefreshLayout pullToRefreshLayout;

    private int pageNo = 1;//当前页数
    //    private int totalpage = 0;//总条数
    private final static int REFRESHING = 0x010;
    private final static int LOADMORE = 0x020;
    int freshState = REFRESHING;//默认是刷新

    @Override
    public int bindLayout() {
        return R.layout.frag_tab_order;
    }

    boolean isEnterAct = false;
    String returnOrderId = "";

    @Override
    public void initView(View view) {
        dialogTwo = new XDialogTwo(this);
        tv_page_title = findView(view, R.id.tv_page_title);
        tv_right = findView(view, R.id.tv_right);
        tv_page_title.setText("订单管理");
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setOnClickListener(this);
        tv_right.setText("收钱");

        tv_tab_left = findView(view, R.id.tv_tab_left);
        tv_tab_center = findView(view, R.id.tv_tab_center);
        tv_tab_right = findView(view, R.id.tv_tab_right);
        tv_tab_left.setOnClickListener(this);
        tv_tab_center.setOnClickListener(this);
        tv_tab_right.setOnClickListener(this);
        tv_tab_left.setText("未处理订单");
        tv_tab_center.setText("已处理订单");
        tv_tab_right.setText("退单");


        pullToRefreshLayout = findView(view, R.id.pullToRefreshLayout);
        pullToRefreshLayout.setRefreshListener(this);

        mListView = findView(view, R.id.mListView);

        listAdapter = new OrderListAdapter(getActivity(), list);
        returnListAdapter = new OrderReturnListAdapter(getActivity(), returnList);
        mListView.setAdapter(listAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (type == 3) {
                    isEnterAct = true;
                    //退
                    Bundle bundle = new Bundle();
                    bundle.putString("goods_return_id", returnList.get(position).getGoods_return_id());
                    bundle.putString("userid", returnList.get(position).getUserid());
                    startActivity(OrderReturnDetailActivity.class, bundle);

                } else {
                    isEnterAct = true;
                    Bundle bundle = new Bundle();
                    bundle.putString("orderId", list.get(position).getOrder_id());
                    startActivity(OrderDetailInfoActivity.class, bundle);

                }

            }
        });
        listAdapter.setAdpListener(new BaseAdp.IAdpBaseListener() {
            @Override
            public void onLazyAdpListener(int key, int position, Object data) {
                switch (key) {
                    case 2:
                        if (type != 3) {
                            showSendGoodsDialog(((OrderListModel) data).getOrder_id());
                        }

                        break;

                }
            }
        });
        returnListAdapter.setAdpListener(new BaseAdp.IAdpBaseListener() {
            @Override
            public void onLazyAdpListener(int key, int position, Object data) {
                switch (key) {
                    case 1:
                        if (type == 3) {
                            returnOrderId = ((OrderRetrunListModel) data).getGoods_return_id();
                            if(((OrderRetrunListModel) data).getReturn_type().equals("1")){
                                dialogTwo.showTwoDialog(getActivity(), "同意退货？", "确定", "取消", "提示", 1);
                            }else{
                                dialogTwo.showTwoDialog(getActivity(), "同意换货？", "确定", "取消", "提示", 1);
                            }

                        }

                        break;

                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isEnterAct) {
            isEnterAct = false;
            refresh();
        }
    }

    @Override
    public void doBusiness(Context mContext) {
        networkRequest = new NetworkRequest(mContext, this);
        tv_tab_left.performClick();
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_right:
                showQrPrice();
                break;
            case R.id.tv_tab_left:
                selected();
                tv_tab_left.setSelected(true);
                type = 1;
                refresh();
                break;
            case R.id.tv_tab_center:
                selected();
                tv_tab_center.setSelected(true);
                type = 2;
                refresh();
                break;
            case R.id.tv_tab_right:
                selected();
                tv_tab_right.setSelected(true);
                type = 3;
                refresh();
                break;
        }
    }

    //重置所有文本的选中状态
    public void selected() {
        tv_tab_left.setSelected(false);
        tv_tab_center.setSelected(false);
        tv_tab_right.setSelected(false);
    }

    @Override
    public void onSubmitClick(int tag) {
        switch (tag) {
            case 1:
                agreeReturnOrder(returnOrderId);
                break;
        }
    }

    @Override
    public void onCancleClick(int tag) {

    }

    /**
     * 输入金额提示
     */
    protected void showTwoDialog() {
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_price);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }

        dialog.getWindow().setAttributes(params);

        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(edt.getText().toString())) {
                    ToastUtil.showShort(getActivity(), "提交成功");
                    dialog.dismiss();
                } else {
                    ToastUtil.showShort(getActivity(), "请输入金额");
                }
            }
        });

    }

    /**
     * 确认发货提示框
     */
    protected void showSendGoodsDialog(final String orderId) {
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_express);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        final EditText edt_order = (EditText) dialog.findViewById(R.id.edt_order);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }

        dialog.getWindow().setAttributes(params);
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edt.setText(s);
                        edt.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edt.setText(s);
                    edt.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edt.setText(s.subSequence(0, 1));
                        edt.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                judgeNumber(s);
            }

        });
        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (TextUtils.isEmpty(edt.getText().toString())) {
                    ToastUtil.showShort(getActivity(), "请输入运费");
                    return;
                }
                if (TextUtils.isEmpty(edt_order.getText().toString())) {
                    ToastUtil.showShort(getActivity(), "请输入运单号");
                    return;
                }
//                ToastUtil.showShort(getActivity(), "发货成功");
                dialog.dismiss();

                subSendGoods(orderId, "无", edt.getText().toString(), edt_order.getText().toString());
            }
        });

    }
    /**
     * 金额输入框中的内容限制（最大：小数点前五位，小数点后2位）
     * @param edt
     */
    public void judgeNumber(Editable edt){

        String temp = edt.toString();
        int posDot = temp.indexOf(".");//返回指定字符在此字符串中第一次出现处的索引
        if (posDot <= 0) {//不包含小数点
            if (temp.length() <= 3) {
                return;//小于五位数直接返回
            } else {
                edt.delete(3, 4);//大于五位数就删掉第六位（只会保留五位）
                return;
            }
        }
        if (temp.length() - posDot - 1 > 2)//如果包含小数点
        {
            edt.delete(posDot + 3, posDot + 4);//删除小数点后的第三位
        }
    }
    /**
     * 获取信息
     */
    private void getOrderListDatas(boolean isShow) {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'storehouse_id' => '', // 门店唯一id
//                'order_type' => 'payment', // 获取订单数据类型  all：全部，untreated：未处理，treated：已处理
//                'psize' => '10', //提交的参数p 每页显示数
//                'p' => '1', //提交的参数p 第几页
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_ServeOrderList);
        parmMap.put("storehouse_id", AppInfo.getUser(getActivity()).getStorehouse_id());//服务站用户id
        switch (type) {
            case 1:
                parmMap.put("order_type", "untreated");
                break;
            case 2:
                parmMap.put("order_type", "treated");
                break;
        }

        parmMap.put("psize", "10");
        parmMap.put("p", pageNo + "");
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_1, isShow, Constant.classes.Order_an_ServeOrderList);
    }

    /**
     * 获取退单信息
     */
    private void getReturnOrder(boolean isShow) {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'storehouse_id' => '', // 门店唯一id
//                'order_type' => 'payment', // 获取订单数据类型  all：全部，untreated：未处理，treated：已处理
//                'psize' => '10', //提交的参数p 每页显示数
//                'p' => '1', //提交的参数p 第几页
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_ServeReturnGoodsList);
        parmMap.put("storehouse_id", AppInfo.getUser(getActivity()).getStorehouse_id());//服务站用户id
        parmMap.put("return_type", "all");
        parmMap.put("psize", "10");
        parmMap.put("p", pageNo + "");
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_2, isShow, Constant.classes.Order_an_ServeReturnGoodsList);
    }

    /**
     * 确认发货
     */
    private void subSendGoods(String orderId, String remark, String freight_money, String logistics_no) {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'storehouse_id' => '', // 门店唯一id
//                'order_id' => '', //
//                'freight_money' => '10', //物流金额
//                'logistics_no' => '1', //物流单号
//                'remark' => '1', //备注
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_ServeOrderConfirm);
        parmMap.put("storehouse_id", AppInfo.getUser(getActivity()).getStorehouse_id());//服务站用户id
        parmMap.put("store_id", AppInfo.getUser(getActivity()).getStore_id());
        parmMap.put("order_id", orderId);
        parmMap.put("freight_money", freight_money);
        parmMap.put("logistics_no", logistics_no);
        parmMap.put("remark", remark);
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_3, true, Constant.classes.Order_an_ServeOrderConfirm);
    }

    /**
     * 同意退换货
     */
    private void agreeReturnOrder(String orderId) {
        /* 修改这里 - 下方为接口所要传递的参数 */
//        'userid' => '', // 用户id 用户端传 没有否则传0
//                'storehouse_id' => '', // 门店id 商户端传 没有否则传0
//                'goods_return_id' => '', // 退货单id
//                'return_type' => 'completion', //  订单类型 ，确认退换货 refundable  ，交易完成 completion
        parmMap = new ArrayMap<>();
        Constant.setCommonParams(parmMap, Constant.App.Order, Constant.classes.Order_an_UpdateReturnState);
        parmMap.put("storehouse_id", AppInfo.getUser(getActivity()).getStorehouse_id());//服务站用户id
        parmMap.put("userid", "0");
        parmMap.put("goods_return_id", orderId);
        parmMap.put("return_type", "refundable");
        networkRequest.postJsonRequest(Constant.serverPath, parmMap, Constant.Actionid.NETWORK_REQUEST_CODE_4, true, Constant.classes.Order_an_UpdateReturnState);
    }

    @Override
    public void onFaild(int orderCode, String result) {
        ToastUtil.showShort(getActivity(), result);
        pullToRefreshLayout.finishLoadMore();
        pullToRefreshLayout.finishRefresh();
    }

    @Override
    public void onSucceed(int orderCode, String result) throws JSONException {
        pullToRefreshLayout.finishLoadMore();
        pullToRefreshLayout.finishRefresh();
        Logger.getLogger(result);
        if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_1) {
            OrderListResponse goodsListResponse = GsonUtil.GsonToBean(result, OrderListResponse.class);
            if (null != goodsListResponse) {

                if (0 == goodsListResponse.getStatus()) {

                    List<OrderListModel> mList = goodsListResponse.getData().getOrder_list();


                    if (null != mList && mList.size() > 0) {
                        if (freshState == REFRESHING) {
                            list.clear();
                            mListView.setAdapter(listAdapter);
                        }
                        list.addAll(mList);
                        listAdapter.setDataList(list);
//                        try {
//                            totalpage = Integer.parseInt(goodsListResponse.getData().getCount());
//                        } catch (NumberFormatException e) {
////                            Log.v(TAG, "返回的总条数不是数字");
//                            e.printStackTrace();
//                        }
                    } else {
                        if (freshState == REFRESHING) {
                            list.clear();
                            mListView.setAdapter(listAdapter);
                            listAdapter.setDataList(null);
                            if (pageNo == 1) {
                                ToastUtil.showShort(getActivity(), "暂无数据");
                            }
                        } else {
                            ToastUtil.showShort(getActivity(), "没有更多数据了");
                        }

                    }

                }


            }


        } else if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_2) {
            OrderReturnListResponse goodsListResponse = GsonUtil.GsonToBean(result, OrderReturnListResponse.class);
            if (null != goodsListResponse) {

                if (0 == goodsListResponse.getStatus()) {

                    List<OrderRetrunListModel> nList = goodsListResponse.getData().getReturn_goods_list();

                    if (null != nList && nList.size() > 0) {
                        if (freshState == REFRESHING) {
                            returnList.clear();
                            mListView.setAdapter(returnListAdapter);
                        }
                        returnList.addAll(nList);
                        returnListAdapter.setDataList(returnList);
//                        try {
//                            totalpage = Integer.parseInt(goodsListResponse.getData().getCount());
//                        } catch (NumberFormatException e) {
////                            Log.v(TAG, "返回的总条数不是数字");
//                            e.printStackTrace();
//                        }
                    } else {
                        if (freshState == REFRESHING) {
                            returnList.clear();
                            mListView.setAdapter(returnListAdapter);
                            returnListAdapter.setDataList(null);
                            if (pageNo == 1) {
                                ToastUtil.showShort(getActivity(), "暂无数据");
                            }
                        } else {
                            ToastUtil.showShort(getActivity(), "没有更多数据了");
                        }

                    }

                }


            }
        } else if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_3) {
            ToastUtil.showShort(getActivity(), "发货成功");
//发货成功
            refresh();
        } else if (orderCode == Constant.Actionid.NETWORK_REQUEST_CODE_4) {
            ToastUtil.showShort(getActivity(), "操作成功");
//同意
            refresh();
        }
    }

    @Override
    public void refresh() {

        freshState = REFRESHING;
        pageNo = 1;
        if (type == 3) {
            getReturnOrder(false);
        } else {
            getOrderListDatas(false);
        }

    }

    @Override
    public void loadMore() {

//        if (pageNo * list.size() < totalpage) {
        freshState = LOADMORE;
        pageNo++;
        if (type == 3) {
            getReturnOrder(false);
        } else {
            getOrderListDatas(false);
        }
//        } else {
//            pullToRefreshLayout.finishLoadMore();
//            ToastUtil.showShort(getActivity(), "没有更多数据了");
//        }

    }

    /**
     * 输入金额提示
     */
    protected void showQrPrice() {
        final Dialog dialog = new Dialog(getActivity(), R.style.Dialog_image);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_input_price);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        final EditText edt = (EditText) dialog.findViewById(R.id.edt_price);
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        Button btn_qx = (Button) dialog.findViewById(R.id.btn_one);
        Button btn_qd = (Button) dialog.findViewById(R.id.btn_two);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        if (!dialog.isShowing()) {
            dialog.show();
        }
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        edt.setText(s);
                        edt.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    edt.setText(s);
                    edt.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        edt.setText(s.subSequence(0, 1));
                        edt.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        dialog.getWindow().setAttributes(params);

        btn_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

            }
        });
        btn_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!TextUtils.isEmpty(edt.getText().toString()) && edt.getText().toString().length() > 0) {
//                    ToastUtil.showShort(MainActivity.this, "提交成功");
                    if (edt.getText().toString().startsWith(".") || edt.getText().toString().endsWith(".")) {
                        ToastUtil.showShort(getActivity(), "请输入正确的金额");
                        return;
                    }
                    dialog.dismiss();
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                    String price = decimalFormat.format(Double.parseDouble(edt.getText().toString()));//format 返回的是字符串
                    isEnterAct = true;
                    Intent m = new Intent(getActivity(), QrPicActivity.class);
                    m.putExtra("price", price);
                    startActivity(m);
                } else {
                    ToastUtil.showShort(getActivity(), "请输入金额");
                }
            }
        });

    }
}
